package csu.web.credit_bank.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import csu.web.credit_bank.mapper.CourseSelectionsMapper;
import csu.web.credit_bank.mapper.CoursesMapper;
import csu.web.credit_bank.pojo.Course;
import csu.web.credit_bank.pojo.CourseSelection;
import csu.web.credit_bank.pojo.CreditRecord;
import csu.web.credit_bank.pojo.CreditSummary;
import csu.web.credit_bank.service.CourseSelectionsService;
import csu.web.credit_bank.service.CreditRecordsService;
import csu.web.credit_bank.service.CreditSummaryService;
import csu.web.credit_bank.utils.UUIDManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; // 确保引入 Transactional

import java.util.Date;
import java.util.List;

@Service
public class CourseSelectionsServiceImpl extends ServiceImpl<CourseSelectionsMapper, CourseSelection> implements CourseSelectionsService {

    // 原始依赖
    @Autowired
    private UUIDManager uuidManager;


    @Autowired
    private CoursesMapper coursesMapper;

    @Autowired
    private CreditSummaryService creditSummaryService;


    @Autowired
    private CreditRecordsService creditRecordsService;


    @Override
    @Transactional // 添加事务注解，确保购买过程的原子性
    public CourseSelection createSelection(String userId, String courseId) {
        //检查用户是否已购买此课程 (复用您已有的 getSelection 方法)
        if (this.getSelection(userId, courseId) != null) {
            throw new IllegalStateException("您已加入该课程，请勿重复购买");
        }

        // 获取课程信息，确定价格
        Course course = coursesMapper.selectById(courseId);
        if (course == null) {
            throw new RuntimeException("课程不存在");
        }
        int coursePrice = course.getCredit();

        //对于价格为0或负数（免费）的课程，直接选课
        if (coursePrice <= 0) {
            return enrollUserForFree(userId, courseId);
        }

        //检查用户学分是否充足
        CreditSummary summary = creditSummaryService.getCreditSummaryByUserId(userId);
        if (summary == null || summary.getCurrentCredits() < coursePrice) {
            throw new RuntimeException("学分不足，无法购买");
        }

        // 扣除学分：创建一条负学分变更记录
        CreditRecord creditRecord = new CreditRecord();
        creditRecord.setUserId(userId);
        creditRecord.setCredits(-coursePrice); // 负值表示支出
        creditRecord.setMethod("课程购买");          // 对应原来的 setChangeType
        creditRecord.setCourseName(course.getName());   // 对应原来的 setChangeDescription
        creditRecord.setRecordTime(new Date());         // 对应原来的 setChangeTime
        creditRecordsService.createCreditRecord(creditRecord);

        //创建选课记录，将用户加入课程
        return enrollUserForFree(userId, courseId);
    }

    /**
     * 辅助方法，用于处理实际的选课记录创建
     */
    private CourseSelection enrollUserForFree(String userId, String courseId) {
        String selectionId = uuidManager.getUUID();
        if (selectionId == null) {
            throw new RuntimeException("ID池已空，选课失败");
        }
        CourseSelection selection = new CourseSelection();
        selection.setId(selectionId);
        selection.setUserId(userId);
        selection.setCourseId(courseId);
        selection.setSelectTime(new Date());
        this.save(selection);
        return selection;
    }



    @Override
    public List<CourseSelection> getSelectionsByUserId(String userId) {
        QueryWrapper<CourseSelection> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        return this.list(wrapper);
    }

    @Override
    public CourseSelection getSelection(String userId, String courseId) {
        QueryWrapper<CourseSelection> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("course_id", courseId);
        return this.getOne(wrapper);
    }

    @Override
    public CourseSelection updateSelection(CourseSelection selection) {
        boolean success = this.updateById(selection);
        if (success) {
            return this.getById(selection.getId());
        }
        return null;
    }

    @Override
    public boolean deleteSelection(String userId, String courseId) {
        QueryWrapper<CourseSelection> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).eq("course_id", courseId);
        return this.remove(wrapper);
    }

    @Override
    public List<CourseSelection> getSelectionsByCourseId(String courseId) {
        QueryWrapper<CourseSelection> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", courseId);
        return this.list(wrapper);
    }
}